package com.neo.subscribe.stamp.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.ImmutableMap;
import com.neo.subscribe.common.util.BeanUtils;
import com.neo.subscribe.stamp.entity.InterfaceConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 【近期热门】请求预处理
 */
@Slf4j
@Service
public class RecentHotRequestPreProcess extends AbstractRequestPreProcess {
    

    @Value("${webdriver.chrome.bin}")
    public String chromeBin;
    
    @Value("${webdriver.chrome.driver}")
    public String chromeDriver;
    /**
     * 爬取的根目录
     */
    @Value("${stamp.root.url}")
    public String ROOT_URL;

    /**
     * cateId 提取正则
     */
    @Value("${stamp.cate.id.regex}")
    public String CATE_ID_REGEX;

    @Override
    public List<InterfaceConfig> process(InterfaceConfig config) {
        String pageSource = openRoot();
        log.info("预处理解析到的页面：{}", pageSource);
        Set<String> cateIds = parseCateIds(pageSource);
        log.info("预处理解析到cateId:{}", JSON.toJSONString(cateIds));
        if (CollectionUtils.isEmpty(cateIds)) {
            return Collections.EMPTY_LIST;
        }
        
        List<InterfaceConfig> result = new ArrayList<>(CollectionUtils.size(cateIds));
        JSONObject json = JSONObject.parseObject(config.getRequestBody());
        for (String cateId : cateIds) {
            InterfaceConfig ic = BeanUtils.copyBeanFromNew(config, InterfaceConfig.class);
            json.put("cateId", cateId);
            ic.setRequestBody(json.toJSONString());
            result.add(ic);
        }
        return result;
    }


    /**
     * CentOS7 安装Selenium+chrome+chromedriver+java 配置参考：https://blog.csdn.net/qq_41595144/article/details/101567571
     * @return
     */
    public String openRoot() {
        WebDriver driver = null;
        try {
            System.setProperty("webdriver.chrome.bin", chromeBin);
            System.setProperty("webdriver.chrome.driver", chromeDriver);
            ChromeOptions options = new ChromeOptions();
            // 无界面参数
            options.addArguments("headless");
            // 禁用沙盒 
            options.addArguments("no-sandbox");
            // 无图模式
            options.setExperimentalOption("prefs", ImmutableMap.of("profile.managed_default_content_settings.images", 2));

            driver = new ChromeDriver(options);
            driver.get(ROOT_URL);
            return driver.getPageSource();
        } finally {
            if (driver != null) {
                driver.quit();
            }
        }
    }

    /**
     * 解析数据
     *
     * @param html
     * @return
     */
    public Set<String> parseCateIds(String html) {
        if (StringUtils.isBlank(html)) {
            return Collections.EMPTY_SET;
        }
        Set<String> result = new HashSet<>();
        Pattern pattern = Pattern.compile(CATE_ID_REGEX);
        // 利用正则去解析
        Matcher matcher = pattern.matcher(html);
        while (matcher.find()) {
            String cateId = matcher.group(1);
            if (StringUtils.isNoneBlank(cateId)) {
                result.add(cateId);
            }
        }
        return result;
    }
}
